import tokenManager from "../utils/manager/tokenManager.js"
// 获取环境变量中的基础URL
import { server as PREFIX } from "../utils/server.js";
const BASE_URL = PREFIX;

// 请求拦截器
function requestInterceptor(options) {
	let { url, method, data, header } = options;
	header = header || {}
	if (!url.startsWith("/login")) {
		let workflow_token = tokenManager.getToken();
		if (!workflow_token) {
			console.log("token为空");
		}
		header["token"] = workflow_token;
		header["Authorization"] = 'Bearer ' + workflow_token;
	}
	let config = {
		url: `${BASE_URL}${url}`,
		method: method || 'GET',
		data: data || {},
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			...header
		}
	}
	return config;
}

// 响应拦截器
function responseInterceptor(response) {
	if (response["header"]["token"]) {
		tokenManager.setToken(response["header"]["token"]);
	}
	return response.data;
}

// 错误处理函数
function handleError(error) {
	console.log('请求出错:', error);
	return error;
}

export function request(options) {
	return new Promise((resolve, reject) => {
		uni.request({
			...requestInterceptor(options),
			success: (response) => {
				resolve(responseInterceptor(response));
			},
			fail: (error) => {
				reject(handleError(error));
			}
		});
	});
}